package ytt.small.fore.controller;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import ytt.small.fore.model.bo.LoginForm;
import ytt.small.fore.model.enums.RespondCodeEnum;
import ytt.small.fore.model.po.UserToken;
import ytt.small.fore.service.UserService;
import ytt.small.fore.service.UserTokenService;
import ytt.small.fore.service.impl.UserServiceImpl;
import ytt.small.fore.utils.RespondResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: small_woods
 * @Date: 2020/6/16 11:49
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserTokenService userTokenService;

    @RequestMapping("/next")
    public String next(){
        RespondResult.success("next!11");
        return "next!111";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, @RequestBody LoginForm loginForm){
        String userName = loginForm.getUserName();
        String password = loginForm.getPassword();
        password = SecureUtil.md5(password);
        if(password.equals(userService.selectByUserName(userName))){
            System.out.println("登录成功！");
            UserToken userToken = userTokenService.create(userName);
            HttpSession session = request.getSession();
            session.setAttribute("userToken",userToken);
            RespondResult.success();
            return userToken.getToken();
        }else{
            System.out.println("失败");
            RespondResult.error(RespondCodeEnum.userNameAndPasswordError);
        }

        return null;
    }
}
